// ActionScript file
import Components.TitleWindow.twHelpContent;

import flash.events.KeyboardEvent;
import flash.ui.Keyboard;

import mx.controls.Alert;
import mx.events.CloseEvent;
import mx.managers.PopUpManager;

import org.flexlancer.Logger.Logger;
import org.flexlancer.databases.Customers;
import org.flexlancer.databases.DatabaseManager;
import org.flexlancer.databases.dbSalesInvoice;
import org.flexlancer.events.TypeInSearchItemSelected;

[Bindable]
private var dpCart:Array = new Array();
private var dpCustomer:Object = new Object();
[Bindable]
private var dpVehicleType:Array = new Array();
[Bindable]
private var dpCustVehicle:Array = new Array();

private var CustomerID:Number = -1;

private function OnCC():void{
	try{
		this.typeinProduct.addEventListener(TypeInSearchItemSelected.ITEM_SELECTED,OnTypeInProductSearch_ItemSelected);
		this.typeinCustomer.addEventListener(TypeInSearchItemSelected.ITEM_SELECTED,OnTypeInCustomerSearch_ItemSelected);
		this.dgCart.addEventListener(KeyboardEvent.KEY_DOWN,OnDataGridKeyDown);
		this.typeinCustomer.txtInput.setFocus();
		this.EnableNewCustomer = false;
		this.canSale.swapChildrenAt(this.canSale.getChildIndex(this.typeinCustomer),this.canSale.numChildren-1);
		this.dpVehicleType.push({label:"4 W",data:"4 Wheeler (Cars)"});
		this.dpVehicleType.push({label:"3 W",data:"3 Wheeler (Rickshaws)"});
		this.dpVehicleType.push({label:"2 W",data:"2 Wheeler (Bikes)"});
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnItemQuantity_Enter():void{
	try{
		this.UpdateCart(this.dpCart[this.lastItemInCartIndex],Number(this.txtItemQuantity.text));
		this.ResetItem();
	}catch(err:Error){
		Logger.LogE(err);
	}
}
private var twHelp:twHelpContent = null;

private function toggleHelp():void{
	try{
		if ( this.twHelp == null ){
			this.twHelp = PopUpManager.createPopUp(this,twHelpContent,true) as twHelpContent;
			PopUpManager.centerPopUp(this.twHelp);
		}else{
			PopUpManager.removePopUp(this.twHelp);
			this.twHelp = null
		}
	}catch(err:Error){
		Logger.LogE(err);
	}
}
private function OnMainKeyDown(evt:KeyboardEvent):void{
	try{
		switch ( evt.keyCode ){
			case Keyboard.F1:
				this.toggleHelp();
			break;
			case Keyboard.F2:
				this.typeinCustomer.txtInput.setFocus();
			break;
			case Keyboard.F3:
				this.typeinProduct.txtInput.setFocus();
			break;
			case Keyboard.F4:
				this.EditCartItem(this.dpCart.length - 1);
				break;
			case Keyboard.F5:
				this.dgCart.setFocus();
			break;
			case Keyboard.F6:
				this.dpCart.pop();
				this.dgCart.dataProvider = this.dpCart;
				this.PopulateTotals();
			break;
			case Keyboard.F10:
				this.AskForReset();
			break;
			case Keyboard.F12:
				this.txtAmountPaidSales.setFocus();
			break;
			default:
			break;
		}
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnAmountPaid_Enter():void{
	try{
		this.OnDoneClick();
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function EditCartItem( index:Number):void{
	try{
		this.lastItemInCartIndex = index;
		if ( index > -1 ){
			var lastItem:Object = this.dpCart[index];
						
			if( lastItem != null ){
				this.typeinProduct.txtInput.text = lastItem.title;
				this.txtItemBarcode.text = lastItem.barcode;
				this.txtItemQuantity.txt_input = lastItem.qty;
				this.txtItemQuantity.text = lastItem.qty;
				if ( lastItem.type == "product" )
					this.txtItemQuantity.maximum = lastItem.instock;
				else
					this.txtItemQuantity.maximum = 100;
					
				this.txtItemQuantity.setFocus();
				this.item_editing = true;
			}		
		}
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnDgCart_KeyUp(evt:KeyboardEvent):void{
	try{
		switch(evt.keyCode){
			case Keyboard.ENTER:
			this.EditCartItem(this.dgCart.selectedIndex);
			break;
		}
	}catch(err:Error){
		Logger.LogE(err);
	}
}
private var lastItemInCartIndex:Number = -1;
private var item_editing:Boolean = false;
private function OnTypeInProductSearch_ItemSelected(evt:TypeInSearchItemSelected):void{
	try{
		this.UpdateCart(evt.Data);
		this.ResetItem();
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function ResetItem():void{
	try{
		this.txtItemBarcode.text = "";
		this.txtItemQuantity.text = "";
		this.typeinProduct.txtInput.text = "";
		this.typeinProduct.txtInput.setFocus();
	}catch(err:Error){
		Logger.LogE(err);
	}
} 

private function UpdateCart(saveObject:Object,itemCount:Number = 1):void{
	try{
		var new_one:Boolean = true;
		for each ( var singleObject:Object in this.dpCart ){
			if ( singleObject.title == saveObject.title ){
				if ( itemCount > 0 ){
					singleObject.qty = itemCount;
				}else{
					this.dpCart.splice(this.lastItemInCartIndex,1);
				}
				new_one = false;
				break;
			}
		}
		
		if ( new_one ){
			saveObject.qty = 1;
			this.dpCart.push(saveObject);
		}
				
		saveObject.total = Number(saveObject.price) * saveObject.qty;
		
		this.dgCart.dataProvider = this.dpCart;
		this.PopulateTotals();
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnTypeInCustomerSearch_ItemSelected(evt:TypeInSearchItemSelected):void{
		//Alert.show(evt.Data.customerid);
	try{
		this.dpCustomer = evt.Data
		this.txtLoyaltyID.text = this.dpCustomer.customerloyalty;
		this.txtPreviousCreditSales.text = this.dpCustomer.credit;
		this.CustomerID = this.dpCustomer.customerid;
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function PopulateTotals(delay:Boolean = true):void{
	try{
		if ( delay ){
			this.callLater(this.PopulateTotals,[false]);
			return;
		}
		var qtys:Number = 0;
		var totals:Number = 0;
		var discount:Number = Number(this.txtDiscountSales.text);
		var amount:Number = Number(this.txtAmountPaidSales.text);
		
		for each ( var item:Object in this.dpCart ){
			qtys += item.qty;
			totals += item.total;
		}
		
		var totalpayable:Number = totals - discount;
		var totalbalance:Number = amount - totals;
		
		this.txtItemCountSales.text = qtys.toString(); 
		this.txtCurrentTotalSales.text = totals.toString();
		this.txtTotalPayableSales.text = totalpayable.toString();
		this.txtBalanceSales.text = totalbalance.toString();
		
		if ( totalbalance < 0 ){
			this.txtBalanceSales.setStyle("color",0xDE3A07);
		}else{
			this.txtBalanceSales.setStyle("color",0x1e7a32);
		}
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnDataGridKeyDown(evt:KeyboardEvent):void{
	try{
		if(evt.keyCode == Keyboard.DELETE){
			//Alert.show("Del press");
			this.PerformDelete();
		}
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function PerformDelete():void{
	try{
		var index:Number = this.dpCart.indexOf(this.dgCart.selectedItem);
		this.dpCart.splice(index,1);
		this.dgCart.dataProvider = this.dpCart;
		this.PopulateTotals();
	}catch( err:Error){
		Logger.LogE(err);
	}
}
private function SaveCustomer():Object{
	try{
		if ( this.chkCreateNew.selected ) {
			var contactdetails:Array = new Array();
			var vehicledetails:Array = new Array();
			
			vehicledetails.push({type:this.cmbVehicleType.selectedItem.data, regnum:this.txtRegistrationNumber.text, detail:this.txtVehicleModelMake.text});
	
			contactdetails.push({type:"Address", detail:this.txtAddress.text});
			contactdetails.push({type:"Mobile", detail:this.txtMobileNumber.text});
	
			Customers.Add(this.typeinCustomer.txtInput.text,"Registered",this.txtLoyaltyID.text,contactdetails,vehicledetails);
			return Customers.List("customerid = "+DatabaseManager.Manager.LastInsertRowID)[0];
		}else{
			return this.dpCustomer;
		}
	}catch(err:Error){
		throw err;
	}
	return null;
}
private function OnDoneClick():void{
	try{
		var a:Boolean,b:Boolean,c:Boolean,d:Boolean,e:Boolean,f:Boolean,g:Boolean,h:Boolean,i:Boolean,j:Boolean = false;
		var custObj:Object = this.SaveCustomer();
		
		if(this.dfSalesDate.selectedDate != null){
			a=true;
		}else{
			Alert.show("Sales date is not selected","Empty Field");
		}
		if(this.txtItemCountSales.text != ""){
			b=true;
		}else{
			Alert.show("Items Count is Empty","Empty Field");
		}
		if(this.txtPreviousCreditSales.text != ""){
			c=true;
		}else{
			Alert.show("Previous credit is Empty","Empty Field");
		}
		if(this.txtCurrentTotalSales.text != ""){
			d=true;
		}else{
			Alert.show("Current Total is Empty","Empty Field");
		}
		if(this.txtDiscountSales.text != ""){
			e=true;
		}else{
			Alert.show("Discount is Empty","Empty Field");
		}
		if(this.txtTotalPayableSales.text != ""){
			f=true;
		}else{
			Alert.show("Total Payable is Empty","Empty Field");
		}
		if(this.txtAmountPaidSales.text != ""){
			g=true;
		}else{
			Alert.show("Amoount Paid is Empty","Empty Field");
		}
		if(this.txtBalanceSales.text != ""){
			h=true;
		}else{
			Alert.show("Balance is Empty","Empty Field");
		}
		/*if(this.dpCart.length >=1){
			i=true;
		}else{
			Alert.show("Products not added","Empty Field");
		}*/
		i = true;
		if(custObj != null){
			j=true;	
		}else{
			Alert.show("Customer not Selected","Empty Field");
		}
		
		if(a && b && c && d && e && f && g && h && i && j){
			var sel_date:String = this.dfSalesDate.selectedDate.fullYear + "/" + this.dfSalesDate.selectedDate.month + "/" + this.dfSalesDate.selectedDate.date;
			var keepBalance:Number = ( this.chkKeepBalance.selected ? 1:0 )
			dbSalesInvoice.Add(custObj.customerid,
			sel_date,
			this.taSalesNote.text,
			Number(this.txtItemCountSales.text),
			Number(this.txtPreviousCreditSales.text),
			Number(this.txtCurrentTotalSales.text),
			Number(this.txtDiscountSales.text),
			Number(this.txtTotalPayableSales.text),
			Number(this.txtAmountPaidSales.text),
			Number(this.txtBalanceSales.text),
			this.dpCart,
			keepBalance
			);

			Alert.show("Sales done Rs."+this.txtTotalPayableSales.text,"Invoice save");

			this.ResetInvoice();
			this.typeinCustomer.txtInput.setFocus();
		}
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function set EnableNewCustomer ( val:Boolean ):void{
	try{
		this.txtAddress.enabled = val;
		this.lnkbtnChooseFromList.enabled = val;
		this.txtMobileNumber.enabled = val;
		this.txtVehicleModelMake.enabled = val;
		this.txtLoyaltyID.enabled = val;
		this.txtRegistrationNumber.visible = val;
		this.cmbVehicleType.enabled = val;
		this.cmbRegNum.visible = !val;
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnResetInvoicConfirmation(evt:CloseEvent):void{
	try{
		if ( evt.detail == Alert.YES ){
			this.ResetInvoice();
		}
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function AskForReset():void{
	try{
		Alert.show("Do you want to reset the Invoice?","Confirmation",Alert.YES | Alert.NO,this, OnResetInvoicConfirmation);
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function ResetInvoice():void{
	try{
		this.typeinCustomer.txtInput.text = "";
		this.dpCustomer = new Object();
		this.dpCart = new Array();
		this.CustomerID = -1;
		this.txtItemCountSales.text = "0";
		this.txtPreviousCreditSales.text = "0";
		this.txtCurrentTotalSales.text = "0";
		this.txtDiscountSales.text = "0";
		this.txtTotalPayableSales.text = "0";
		this.txtAmountPaidSales.text = "0";
		this.txtBalanceSales.text = "0";
		this.taSalesNote.text = "";
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function chkNewCustomer_OnChange():void{
	try{
		this.typeinCustomer.DisableSearch = this.chkCreateNew.selected;
		this.EnableNewCustomer = this.chkCreateNew.selected;
	}catch(err:Error){
		Logger.LogE(err);
	}
}